﻿
using System;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using Core.AdminGroupMenuPermission;
using Core.Authenticated;
using Core.Library;
using DataObject;
using DataObject.Cache;
using DataObject.QA;

namespace CMS.Controls.QA
{
    public partial class QAManager : AuthenticatedControl
    {
        #region Variables

        protected string Tab;
        protected string Url;
        protected int PageIndex;
        protected int PageSize;
        protected int WaitingForPublish;
        protected int Publish;

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            Tab = Utils.GetIdFromRequestString(Utils.Tab, string.Empty);

            if (string.IsNullOrEmpty(Tab))
                Response.Redirect(UrlHelpers.ListTab(cControl.AdminMenuId, Utils.IsPublished));

            PageIndex = Utils.GetIdFromRequestString(Utils.PageIndex, SettingValues.PageIndex);
            PageSize = Utils.GetIdFromRequestString(Utils.PageSize, ConvertUtility.ConvertTo<int>(ddlPageSize.SelectedValue));
            Url = HttpUtility.UrlEncode(Request.Url.ToString());

            if (!IsPostBack)
            {
                InitArticle();
                ListData();
                GetStatistics();
            }
        }

        #region Statistics

        private void GetStatistics()
        {
            WaitingForPublish = QAController.Question_GetStatistic(false);
            Publish = QAController.Question_GetStatistic(true);
        }

        #endregion

        #region Bind Data

        private void InitArticle()
        {
            var isShowPublished = false;

            var adminGroupMenuPermission =
                    AdminGroupMenuPermissionController.AdminGroupMenuPermission_GetBy_AdminUserId_AdminMenuId(CurrentUser.AdminUserId, cControl.AdminMenuId);
            if (adminGroupMenuPermission.Count > 0)
            {
                foreach (var agmp in adminGroupMenuPermission)
                {
                    isShowPublished = StatusHelper.IsChecked(agmp.Status, (int)PermissionObject.CanPublish);
                }
            }

            hfTab.Value = Tab;
            if (!string.IsNullOrEmpty(hfTab.Value))
            {
                switch (hfTab.Value)
                {
                    case "IsWaitingForPublish":
                        hfIsActive.Value = "false";
                        btnPublish.Visible = isShowPublished;
                        btnDelete.Visible = isShowPublished;
                        break;
                    case "IsPublished":
                        hfIsActive.Value = "true";
                        btnDelete.Visible = isShowPublished;
                        btnRemove.Visible = isShowPublished;
                        break;
                }
            }
            else
            {
                btnPublish.Enabled = false;
                btnDelete.Enabled = false;
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Không lấy được dữ liệu.", MessageType.Failure);
            }
        }

        private void ListData()
        {

            lvList.DataSource = QAController.Question_GetListByTypeByStatusPaging(ConvertUtility.ConvertTo<bool>(hfIsActive.Value),
                                                                                PageIndex, PageSize);
            lvList.DataBind();

            var totalRecords = QAController.Question_GetStatistic(ConvertUtility.ConvertTo<bool>(hfIsActive.Value));

            ltPager.Text = PagerUtility.PageLinks(PageIndex, PageSize, totalRecords, 5,
                                UrlHelpers.ListSearch(cControl.AdminMenuId, hfTab.Value, "{0}", PageSize));

            ddlPageSize.SelectedValue = PageSize.ToString();
        }

        protected void lvList_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var ltImage = (Literal)e.Item.FindControl("ltImage");
                var status = ConvertUtility.ConvertTo<bool>(((HiddenField)e.Item.FindControl("hfIsFeature")).Value);

                var imgIcon = "<img src=\"\" class=\"floatright mr5 topDir\" title=\"\" alt=\"\"/>";

                if (status)
                    imgIcon = "<img src=\"/images/icons/color/pin.png\" class=\"floatright mr5 topDir btn14\" title=\"Câu hỏi thường gặp\" alt=\"\"/>";

                ltImage.Text = imgIcon;
            }
        }
        #endregion

        #region Action

        private void UpdateStatus(string action)
        {
            ltMessage.Text = string.Empty;
            var count = 0;
            foreach (ListViewDataItem lvi in lvList.Items)
            {
                var cbItem = (CheckBox)lvi.FindControl("cbItem");
                if (cbItem == null || !cbItem.Checked) continue;

                count++;
                var id = ConvertUtility.ConvertTo<int>(lvList.DataKeys[lvi.DisplayIndex].Value);
                if (id > 0)
                {
                    switch (action)
                    {
                        case Const.Action.Delete:
                            QAController.QA_Answer_DeleteAll(id);
                            QAController.QA_Delete(id);
                            break;
                        case Const.Action.Remove:
                            QAController.Question_Update_Status(id, false);
                            break;
                        case Const.Action.Publish:
                            QAController.Question_Update_Status(id, true);
                            break;
                    }
                }
            }

            if (count == 0)
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Bạn chưa chọn bài viết nào.", MessageType.Warning);
            else CacheController.RemoveCachePort(Constants.ManagerCacheGroup.QA);

            ListData();
            GetStatistics();
        }

        protected void BtnPublish(object sender, EventArgs e)
        {
            UpdateStatus(Const.Action.Publish);
        }

        protected void BtnDelete(object sender, EventArgs e)
        {
            UpdateStatus(Const.Action.Delete);
        }

        protected void BtnRemove(object sender, EventArgs e)
        {
            UpdateStatus(Const.Action.Remove);
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirectLink(ConvertUtility.ConvertTo<int>(ddlPageSize.SelectedValue));
        }

        public void RedirectLink(int currentPageSize)
        {
            Response.Redirect(UrlHelpers.ListSearch(cControl.AdminMenuId,
                                                        hfTab.Value,
                                                        SettingValues.PageIndex.ToString(), currentPageSize));
        }

        #endregion
    }
}